import { history } from '@/utils/history'
import { Button, Form, Input, NavBar } from 'antd-mobile'
import styles from './index.module.scss'
import { useLogin } from './service'

export type LoginParams = {
  mobile: string
  code: string
}
const Login = () => {
  const { onFinish, getCode, form, mobileRef, time, codeRef, timeOut } =
    useLogin()
  return (
    <div className={styles.root}>
      <div className="login-form">
        <NavBar
          className="navbar"
          style={{
            '--border-bottom': '1px solid #F0F0F0',
          }}
          onBack={() => history.push('/')}>
          <h2 className="title">账号登录</h2>
        </NavBar>

        {/* 表单结构 */}
        <Form onFinish={onFinish} form={form}>
          {/* 手机号 */}
          <Form.Item
            className="login-item"
            name={'mobile'}
            rules={[
              { required: true, message: '手机号不能为空!' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
              },
            ]}>
            <Input ref={mobileRef} placeholder="请输入手机号" />
          </Form.Item>
          {/* 验证码 */}
          <Form.Item
            className="login-item"
            name={'code'}
            rules={[
              {
                required: true,
                message: '验证码不能为空!',
                len: 6,
              },
            ]}
            extra={
              <span
                onClick={time === 0 ? getCode : undefined}
                className="code-extra">
                {time === 0 ? '发送验证码' : '请' + timeOut(1) + '秒后重试'}
              </span>
            }>
            <Input
              ref={codeRef}
              placeholder="请输入验证码"
              autoComplete="off"
            />
          </Form.Item>
          {/* 提交按钮 */}
          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {() => {
              const isHandle = form.isFieldsTouched(true)
              const isPass = form.getFieldsError(['mobile', 'code'])
              const pass = isPass.every((item) => !item.errors.length)
              let disabled = !(isHandle && pass)
              return (
                <Button
                  block
                  type="submit"
                  color="primary"
                  disabled={disabled}
                  className="login-submit">
                  登 录
                </Button>
              )
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
